/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pe.edu.pucp.cpnc.mm.view;

import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import pe.edu.pucp.cpnc.mm.bean.*;
import pe.edu.pucp.cpnc.mm.manager.CmdManager;
import pe.edu.pucp.cpnc.mm.manager.SaveStateManager;
import pe.edu.pucp.cpnc.mm.renderer.CameraPanController;
import pe.edu.pucp.cpnc.mm.renderer.Renderer;
import pe.edu.pucp.cpnc.mm.resdb.ManagerDB;

/**
 *
 * @author Usuario
 */
public class MainFrame extends javax.swing.JFrame {
    public static Renderer rd = new Renderer();    
    public static ManagerDB resources;
    
    //All of these constants must be places in the main window of the map editor.
    public static pe.edu.pucp.cpnc.mm.bean.Object selObj;
    public static int selectedOrientation=0;
    
    public static Player selectedPlayer = null;
    public static Tile selectedTile = null;
    public static int selectedBrushSize = 1;
    
    private DefaultMutableTreeNode root;
    private MapViewerPanel workingArea = null;
    
    /**
     * Creates new form UnicaPantalla
     */
    public MainFrame() {
        CmdManager.loadDB("Resources.xml");
        resources = CmdManager.getDb();
        
        root = new DefaultMutableTreeNode("top");
        createTree(root);
        
        //Create the background image labels
        JLabel jL2 = new JLabel(new ImageIcon("src/res/MenuFondo.png"));
        jL2.setBounds(0, 0, 1024, 768);
        JLabel jL4 = new JLabel(new ImageIcon("src/res/MenuFondo.png"));
        jL4.setBounds(0, 0, 1024, 768);
        
        initComponents();
        jScrollPane1.getViewport().setOpaque(false);
        
        MapOptionsPane.add(jL2);
        TerrainOptionsPane.add(jL4);        
        
        jLabel1.setForeground(Color.WHITE);
        jLabel4.setForeground(Color.WHITE);
        jLabel5.setForeground(Color.WHITE);
        
        Font f1 = jLabel1.getFont();
        Font f2 = jLabel2.getFont();
        Font f3 = jLabel4.getFont();
        Font f4 = jLabel5.getFont();
        
        jLabel1.setFont(f1.deriveFont(f1.getStyle() | Font.BOLD));
        jLabel2.setFont(f1.deriveFont(f2.getStyle() | Font.BOLD));
        jLabel4.setFont(f1.deriveFont(f3.getStyle() | Font.BOLD));
        jLabel5.setFont(f1.deriveFont(f4.getStyle() | Font.BOLD));
        
        objectJTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        
        createCloseMinimizeButtons();
        TerrainOptionsPane.setVisible(false);
        Unit1OptionsPane.setVisible(false);
        
        //Initializes the Default Tile combo box.
        Tile[] tileArr = resources.getAvailableTiles().toArray(new Tile[resources.getAvailableTiles().size()]);
        cbDefaultTerr.setModel(new DefaultComboBoxModel(tileArr));
        
        cbBrushSize.setModel(new DefaultComboBoxModel(new String[]{"1x1", "3x3", "5x5"}));
       
        this.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
        pack();
    }
    
    //Called whenever there is a new map, be it loaded or created.
    private void reloadMap(Map map){
        if(map!=null){
            if(workingArea!=null) workingAreaCont.remove(workingArea);
            workingArea = new MapViewerPanel(map);
            
            Player[] pArr = new Player[map.getPlayers().size()-1];
            int i = 0;
            for(Player p : map.getPlayers()){
                if(p.getId()!=0){
                    pArr[i] = p;
                    i++;
                }
            }
            cbPlayer.setModel(new DefaultComboBoxModel(pArr));
            cbPlayer.setSelectedIndex(0);
            selectedPlayer=map.getPlayers().get(1);
            
            CameraPanController.setCameraLimits(map.getSizeX(), map.getSizeY(), Renderer.Anchura, 
                    Renderer.Altura, this.getWidth() -395, this.getHeight());
            workingAreaCont.add(workingArea, BorderLayout.CENTER);
            rd.renderInitMinimap(map, miniMapPane);
            
            CmdManager.svm = new SaveStateManager(10, map);
            menuItemRedo.setEnabled(true);
            if(menuItemUndo.isEnabled()==false) menuItemUndo.setEnabled(true);
        }
    }
    
    private MapViewerPanel getCurrentWorkingArea(){
        return workingArea;
    }
    
    public Map getMap(){
        MapViewerPanel pan = getCurrentWorkingArea();
        if(pan!=null){
            return pan.getMap();
        }else{
            return null;
        }
    }
    
    public MapViewerPanel getWorkingArea(){
        return workingArea;
    }
    
    //Creates the JTree structure, and adds it to the root node.
    private void createTree(DefaultMutableTreeNode root){
        DefaultMutableTreeNode category = new DefaultMutableTreeNode("Units");
        for(Unit u : resources.getAvailableUnits()){
            category.add(new DefaultMutableTreeNode(u));
        }
        root.add(category);
        
        category = new DefaultMutableTreeNode("Buildings");
        for(Building u : resources.getAvailableBuildings()){
            category.add(new DefaultMutableTreeNode(u));
        }
        root.add(category);
        
        category = new DefaultMutableTreeNode("Nature");
        for(Nature u : resources.getAvailableNature()){
            category.add(new DefaultMutableTreeNode(u));
        }
        root.add(category);
    }
    
    private void createCloseMinimizeButtons(){
        Container c = new Container();
        c.setLayout(new FlowLayout(FlowLayout.RIGHT));
        
        JButton closeButton = new JButton((Icon)UIManager.get("InternalFrame.closeIcon"));
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                menuItemExitActionPerformed(e);
            }
        });
        JButton minimizeButton = new JButton((Icon)UIManager.get("InternalFrame.iconifyIcon"));
        minimizeButton.setToolTipText("Haz clic en este botón para minimizar la ventana.");
        minimizeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setState(Frame.ICONIFIED);
            }
        });
        c.add(minimizeButton);
        c.add(closeButton);
        mainMenuBar.add(c);
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        backgroundPanel = new javax.swing.JPanel();
        sideSplitPanel = new javax.swing.JPanel();
        miniMapPane = new pe.edu.pucp.cpnc.mm.view.MinimapPanel(this);
        OptionsPanel = new javax.swing.JPanel();
        TabPanel = new javax.swing.JPanel();
        tabMap = new javax.swing.JButton();
        tabUnits = new javax.swing.JButton();
        tabTerrain = new javax.swing.JButton();
        OverlayPanel = new javax.swing.JPanel();
        MapOptionsPane = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        cbDefaultTerr = new javax.swing.JComboBox();
        txtMapName = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        Unit1OptionsPane = new javax.swing.JPanel(){
            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(rd.getSprite("texture"),0,0,getWidth(),getHeight(),this);
            }
        }
        ;
        jLabel2 = new javax.swing.JLabel();
        cbPlayer = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        objectJTree = new javax.swing.JTree(root);
        TerrainOptionsPane = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbBrushSize = new javax.swing.JComboBox();
        tileButton1 = new pe.edu.pucp.cpnc.mm.view.TileButton(resources.getAvailableTiles().get(0));
        tileButton2 = new pe.edu.pucp.cpnc.mm.view.TileButton(resources.getAvailableTiles().get(1));
        tileButton3 = new pe.edu.pucp.cpnc.mm.view.TileButton(resources.getAvailableTiles().get(2));
        workingAreaCont = new javax.swing.JPanel(){
            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(rd.getScaledImage("texture", "textureWKA", this.getWidth(), this.getHeight()),0, 0, this);
            }
        };
        mainMenuBar = new javax.swing.JMenuBar(){
            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(MainFrame.rd.getScaledImage("menuBar", "menuBarSCL", this.getWidth(), this.getHeight())
                    ,0, 0, this);
            }
        };
        jMenu1 = new javax.swing.JMenu();
        menuItemNew = new javax.swing.JMenuItem();
        menuItemOpen = new javax.swing.JMenuItem();
        menuItemSave = new javax.swing.JMenuItem();
        menuItemSaveAs = new javax.swing.JMenuItem();
        menuItemExport = new javax.swing.JMenuItem();
        menuItemExit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        menuItemUndo = new javax.swing.JMenuItem();
        menuItemRedo = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        backgroundPanel.setPreferredSize(new java.awt.Dimension(1196, 1035));
        backgroundPanel.setLayout(new java.awt.BorderLayout(5, 5));

        sideSplitPanel.setLayout(new javax.swing.BoxLayout(sideSplitPanel, javax.swing.BoxLayout.PAGE_AXIS));

        miniMapPane.setMaximumSize(new java.awt.Dimension(300, 300));
        miniMapPane.setMinimumSize(new java.awt.Dimension(300, 300));
        miniMapPane.setPreferredSize(new java.awt.Dimension(300, 300));

        javax.swing.GroupLayout miniMapPaneLayout = new javax.swing.GroupLayout(miniMapPane);
        miniMapPane.setLayout(miniMapPaneLayout);
        miniMapPaneLayout.setHorizontalGroup(
            miniMapPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
        miniMapPaneLayout.setVerticalGroup(
            miniMapPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        sideSplitPanel.add(miniMapPane);

        OptionsPanel.setLayout(new javax.swing.BoxLayout(OptionsPanel, javax.swing.BoxLayout.Y_AXIS));

        TabPanel.setMaximumSize(new java.awt.Dimension(300, 35));
        TabPanel.setMinimumSize(new java.awt.Dimension(300, 35));
        TabPanel.setPreferredSize(new java.awt.Dimension(300, 35));
        java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT);
        flowLayout1.setAlignOnBaseline(true);
        TabPanel.setLayout(flowLayout1);

        tabMap.setText("Map");
        tabMap.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                tabMapMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                tabMapMouseExited(evt);
            }
        });
        tabMap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tabMapActionPerformed(evt);
            }
        });
        TabPanel.add(tabMap);

        tabUnits.setText("Units");
        tabUnits.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                tabUnitsMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                tabUnitsMouseExited(evt);
            }
        });
        tabUnits.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tabUnitsActionPerformed(evt);
            }
        });
        TabPanel.add(tabUnits);

        tabTerrain.setText("Terrain");
        tabTerrain.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                tabTerrainMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                tabTerrainMouseExited(evt);
            }
        });
        tabTerrain.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tabTerrainActionPerformed(evt);
            }
        });
        TabPanel.add(tabTerrain);

        OptionsPanel.add(TabPanel);

        OverlayPanel.setPreferredSize(new java.awt.Dimension(300, 700));
        OverlayPanel.setLayout(new javax.swing.OverlayLayout(OverlayPanel));

        MapOptionsPane.setMinimumSize(new java.awt.Dimension(300, 0));
        MapOptionsPane.setPreferredSize(new java.awt.Dimension(300, 700));

        jLabel4.setText("Default Terrain");

        jLabel5.setText("Map Name");

        cbDefaultTerr.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbDefaultTerrItemStateChanged(evt);
            }
        });
        cbDefaultTerr.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                cbDefaultTerrMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                cbDefaultTerrMouseExited(evt);
            }
        });

        txtMapName.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                txtMapNameMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                txtMapNameMouseExited(evt);
            }
        });

        jButton1.setText("Clear Map");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jButton1MouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jButton1MouseExited(evt);
            }
        });

        javax.swing.GroupLayout MapOptionsPaneLayout = new javax.swing.GroupLayout(MapOptionsPane);
        MapOptionsPane.setLayout(MapOptionsPaneLayout);
        MapOptionsPaneLayout.setHorizontalGroup(
            MapOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(MapOptionsPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(MapOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtMapName)
                    .addGroup(MapOptionsPaneLayout.createSequentialGroup()
                        .addGroup(MapOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(MapOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel5)
                                .addComponent(cbDefaultTerr, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jButton1))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        MapOptionsPaneLayout.setVerticalGroup(
            MapOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(MapOptionsPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbDefaultTerr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMapName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(1544, Short.MAX_VALUE))
        );

        OverlayPanel.add(MapOptionsPane);

        Unit1OptionsPane.setPreferredSize(new java.awt.Dimension(300, 700));

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Player");

        cbPlayer.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbPlayerItemStateChanged(evt);
            }
        });
        cbPlayer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                cbPlayerMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                cbPlayerMouseExited(evt);
            }
        });

        jScrollPane1.setOpaque(false);

        objectJTree.setRootVisible(false);
        objectJTree.setShowsRootHandles(true);
        objectJTree.setCellRenderer(new DefaultUnitTreeCellRenderer());
        objectJTree.setOpaque(false);
        objectJTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                objectJTreeValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(objectJTree);

        javax.swing.GroupLayout Unit1OptionsPaneLayout = new javax.swing.GroupLayout(Unit1OptionsPane);
        Unit1OptionsPane.setLayout(Unit1OptionsPaneLayout);
        Unit1OptionsPaneLayout.setHorizontalGroup(
            Unit1OptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(Unit1OptionsPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(Unit1OptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(Unit1OptionsPaneLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbPlayer, 0, 238, Short.MAX_VALUE)))
                .addContainerGap())
        );
        Unit1OptionsPaneLayout.setVerticalGroup(
            Unit1OptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(Unit1OptionsPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(Unit1OptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cbPlayer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1661, Short.MAX_VALUE)
                .addContainerGap())
        );

        OverlayPanel.add(Unit1OptionsPane);

        TerrainOptionsPane.setPreferredSize(new java.awt.Dimension(300, 700));

        jLabel1.setText("Brush Size");

        cbBrushSize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbBrushSize.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbBrushSizeItemStateChanged(evt);
            }
        });
        cbBrushSize.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                cbBrushSizeMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                cbBrushSizeMouseExited(evt);
            }
        });

        tileButton1.setText("tileButton1");

        tileButton2.setText("tileButton1");

        tileButton3.setText("tileButton1");

        javax.swing.GroupLayout TerrainOptionsPaneLayout = new javax.swing.GroupLayout(TerrainOptionsPane);
        TerrainOptionsPane.setLayout(TerrainOptionsPaneLayout);
        TerrainOptionsPaneLayout.setHorizontalGroup(
            TerrainOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(TerrainOptionsPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(TerrainOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(cbBrushSize, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(TerrainOptionsPaneLayout.createSequentialGroup()
                        .addComponent(tileButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tileButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tileButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(135, Short.MAX_VALUE))
        );
        TerrainOptionsPaneLayout.setVerticalGroup(
            TerrainOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(TerrainOptionsPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(TerrainOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(tileButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addGroup(TerrainOptionsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(tileButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                        .addComponent(tileButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(67, 67, 67)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbBrushSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        OverlayPanel.add(TerrainOptionsPane);

        OptionsPanel.add(OverlayPanel);

        sideSplitPanel.add(OptionsPanel);

        backgroundPanel.add(sideSplitPanel, java.awt.BorderLayout.WEST);

        workingAreaCont.setPreferredSize(new java.awt.Dimension(2000, 1035));
        workingAreaCont.setLayout(new java.awt.BorderLayout());
        backgroundPanel.add(workingAreaCont, java.awt.BorderLayout.CENTER);

        getContentPane().add(backgroundPanel, java.awt.BorderLayout.CENTER);

        mainMenuBar.setBorder(null);

        jMenu1.setForeground(new java.awt.Color(255, 255, 255));
        jMenu1.setText("File");
        jMenu1.setFont(new java.awt.Font("Segoe UI", 1, 20)); // NOI18N

        menuItemNew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        menuItemNew.setText("New");
        menuItemNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemNewActionPerformed(evt);
            }
        });
        jMenu1.add(menuItemNew);

        menuItemOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        menuItemOpen.setText("Open");
        menuItemOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemOpenActionPerformed(evt);
            }
        });
        jMenu1.add(menuItemOpen);

        menuItemSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        menuItemSave.setText("Save");
        menuItemSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemSaveActionPerformed(evt);
            }
        });
        jMenu1.add(menuItemSave);

        menuItemSaveAs.setText("Save As...");
        jMenu1.add(menuItemSaveAs);

        menuItemExport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        menuItemExport.setText("Export");
        menuItemExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemExportActionPerformed(evt);
            }
        });
        jMenu1.add(menuItemExport);

        menuItemExit.setText("Exit");
        menuItemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemExitActionPerformed(evt);
            }
        });
        jMenu1.add(menuItemExit);

        mainMenuBar.add(jMenu1);

        jMenu2.setForeground(new java.awt.Color(255, 255, 255));
        jMenu2.setText("Edit");
        jMenu2.setFont(new java.awt.Font("Segoe UI", 1, 20)); // NOI18N

        menuItemUndo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK));
        menuItemUndo.setText("Undo");
        menuItemUndo.setEnabled(false);
        menuItemUndo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemUndoActionPerformed(evt);
            }
        });
        jMenu2.add(menuItemUndo);

        menuItemRedo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK));
        menuItemRedo.setText("Redo");
        menuItemRedo.setEnabled(false);
        menuItemRedo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemRedoActionPerformed(evt);
            }
        });
        jMenu2.add(menuItemRedo);

        mainMenuBar.add(jMenu2);

        setJMenuBar(mainMenuBar);
    }// </editor-fold>//GEN-END:initComponents

    private void menuItemSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemSaveActionPerformed
        MapViewerPanel pan = getCurrentWorkingArea();
        if(pan!=null){
            Map map = pan.getMap();
            CmdManager.save(map, map.getName() + ".xml");
            JOptionPane.showMessageDialog(null,"Map saved succesfully","Message",JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_menuItemSaveActionPerformed

    private void cbDefaultTerrItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbDefaultTerrItemStateChanged
        if(evt.getStateChange()==ItemEvent.SELECTED){
            Tile tile = (Tile)evt.getItem();
            Map map = getMap();
            if(map!=null){
                CmdManager.changeAllTiles(tile, map);
                rd.renderInitMinimap(map, miniMapPane);
            }
        }
    }//GEN-LAST:event_cbDefaultTerrItemStateChanged

    private void objectJTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_objectJTreeValueChanged
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                       objectJTree.getLastSelectedPathComponent();

        if (node == null)
        //Nothing is selected.     
        return;

        java.lang.Object nodeInfo = node.getUserObject();
        if (node.isLeaf()) {
            selObj = (pe.edu.pucp.cpnc.mm.bean.Object)nodeInfo;
            selectedOrientation = 0;
            selectedTile = null;
        }
    }//GEN-LAST:event_objectJTreeValueChanged

    private void cbPlayerItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbPlayerItemStateChanged
        if(evt.getStateChange()==ItemEvent.SELECTED){
            selectedPlayer = (Player)evt.getItem();
        }
    }//GEN-LAST:event_cbPlayerItemStateChanged

    private void menuItemUndoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemUndoActionPerformed
        Map prevMap = CmdManager.svm.undo();
        if(prevMap!=null){
            getCurrentWorkingArea().setMap(prevMap);
            rd.renderInitMinimap(prevMap, miniMapPane);
        }
    }//GEN-LAST:event_menuItemUndoActionPerformed

    private void menuItemNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemNewActionPerformed
        NewMapDialog newMapDialog = new NewMapDialog(this, Dialog.ModalityType.APPLICATION_MODAL);
        Map map = newMapDialog.showDialog();
        reloadMap(map);
    }//GEN-LAST:event_menuItemNewActionPerformed

    private void menuItemOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemOpenActionPerformed
        JFileChooser fc = new JFileChooser("./");
        int returnVal = fc.showOpenDialog(menuItemOpen);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            String mapName = file.getName();
            System.out.println(mapName);
            Map map = CmdManager.load(mapName);
            if(map!=null)
                reloadMap(map);
            else
                JOptionPane.showMessageDialog(this, "The file could not be opened, it has an incorrect format.", "File Open Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_menuItemOpenActionPerformed

    private void menuItemRedoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemRedoActionPerformed
        Map nextMap = CmdManager.svm.redo();
        if(nextMap!=null){
            getCurrentWorkingArea().setMap(nextMap);
            rd.renderInitMinimap(nextMap, miniMapPane);
        }
    }//GEN-LAST:event_menuItemRedoActionPerformed

    private void menuItemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemExitActionPerformed
        this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
        setVisible(false);
        dispose();
        System.exit(0);
    }//GEN-LAST:event_menuItemExitActionPerformed

    private void tabMapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tabMapActionPerformed
        MapOptionsPane.setVisible(true);
        TerrainOptionsPane.setVisible(false);
        Unit1OptionsPane.setVisible(false);
        OverlayPanel.repaint();
    }//GEN-LAST:event_tabMapActionPerformed

    private void tabUnitsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tabUnitsActionPerformed
        MapOptionsPane.setVisible(false);
        TerrainOptionsPane.setVisible(false);
        Unit1OptionsPane.setVisible(true);
        OverlayPanel.repaint();
    }//GEN-LAST:event_tabUnitsActionPerformed

    private void tabTerrainActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tabTerrainActionPerformed
        MapOptionsPane.setVisible(false);
        TerrainOptionsPane.setVisible(true);
        Unit1OptionsPane.setVisible(false);
        OverlayPanel.repaint();
    }//GEN-LAST:event_tabTerrainActionPerformed

    private void cbBrushSizeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbBrushSizeItemStateChanged
        if(evt.getStateChange() == ItemEvent.SELECTED){
            selectedBrushSize = cbBrushSize.getSelectedIndex()+1;
        }
    }//GEN-LAST:event_cbBrushSizeItemStateChanged

    private void menuItemExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemExportActionPerformed
        MapViewerPanel pan = getCurrentWorkingArea();
        if (pan != null) {
            Map map = pan.getMap();
            CmdManager.export(map, map.getName() + ".txt");
            JOptionPane.showMessageDialog(null, "Map exported succesfully", "Message", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_menuItemExportActionPerformed

    private void tabMapMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabMapMouseEntered
        if(workingArea!=null) workingArea.changeToolTipText("Click this button to change map settings.");
    }//GEN-LAST:event_tabMapMouseEntered

    private void tabMapMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabMapMouseExited
        if(workingArea!=null) workingArea.changeToolTipText("");
    }//GEN-LAST:event_tabMapMouseExited

    private void tabUnitsMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabUnitsMouseEntered
        if(workingArea!=null) workingArea.changeToolTipText("Click this button to add units and buildings.");
    }//GEN-LAST:event_tabUnitsMouseEntered

    private void tabUnitsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabUnitsMouseExited
        if(workingArea!=null) workingArea.changeToolTipText("");
    }//GEN-LAST:event_tabUnitsMouseExited

    private void tabTerrainMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabTerrainMouseEntered
        if(workingArea!=null) workingArea.changeToolTipText("Click this button to change the terrain.");
    }//GEN-LAST:event_tabTerrainMouseEntered

    private void tabTerrainMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabTerrainMouseExited
        if(workingArea!=null) workingArea.changeToolTipText("");
    }//GEN-LAST:event_tabTerrainMouseExited

    private void cbDefaultTerrMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbDefaultTerrMouseEntered
        if(workingArea!=null) workingArea.changeToolTipText("Changes all the map terrain at once.");
    }//GEN-LAST:event_cbDefaultTerrMouseEntered

    private void cbDefaultTerrMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbDefaultTerrMouseExited
        if(workingArea!=null) workingArea.changeToolTipText("");
    }//GEN-LAST:event_cbDefaultTerrMouseExited

    private void txtMapNameMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtMapNameMouseEntered
        if(workingArea!=null) workingArea.changeToolTipText("Changes the map name.");
    }//GEN-LAST:event_txtMapNameMouseEntered

    private void txtMapNameMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtMapNameMouseExited
        if(workingArea!=null) workingArea.changeToolTipText("");
    }//GEN-LAST:event_txtMapNameMouseExited

    private void jButton1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseEntered
        if(workingArea!=null) workingArea.changeToolTipText("Erases all the map units and buildings.");
    }//GEN-LAST:event_jButton1MouseEntered

    private void jButton1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseExited
        if(workingArea!=null) workingArea.changeToolTipText("");
    }//GEN-LAST:event_jButton1MouseExited

    private void cbPlayerMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbPlayerMouseEntered
        if(workingArea!=null) workingArea.changeToolTipText("Select the player for the object to be placed.");
    }//GEN-LAST:event_cbPlayerMouseEntered

    private void cbPlayerMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbPlayerMouseExited
        if(workingArea!=null) workingArea.changeToolTipText("");
    }//GEN-LAST:event_cbPlayerMouseExited

    private void cbBrushSizeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbBrushSizeMouseEntered
        if(workingArea!=null) workingArea.changeToolTipText("Select the brush area size.");
    }//GEN-LAST:event_cbBrushSizeMouseEntered

    private void cbBrushSizeMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cbBrushSizeMouseExited
        if(workingArea!=null) workingArea.changeToolTipText("");
    }//GEN-LAST:event_cbBrushSizeMouseExited

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                MainFrame mf = new MainFrame();
                mf.setVisible(true);
                mf.repaint();
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel MapOptionsPane;
    private javax.swing.JPanel OptionsPanel;
    private javax.swing.JPanel OverlayPanel;
    private javax.swing.JPanel TabPanel;
    private javax.swing.JPanel TerrainOptionsPane;
    private javax.swing.JPanel Unit1OptionsPane;
    private javax.swing.JPanel backgroundPanel;
    private javax.swing.JComboBox cbBrushSize;
    private javax.swing.JComboBox cbDefaultTerr;
    private javax.swing.JComboBox cbPlayer;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuBar mainMenuBar;
    private javax.swing.JMenuItem menuItemExit;
    private javax.swing.JMenuItem menuItemExport;
    private javax.swing.JMenuItem menuItemNew;
    private javax.swing.JMenuItem menuItemOpen;
    private javax.swing.JMenuItem menuItemRedo;
    private javax.swing.JMenuItem menuItemSave;
    private javax.swing.JMenuItem menuItemSaveAs;
    private javax.swing.JMenuItem menuItemUndo;
    public static javax.swing.JPanel miniMapPane;
    private javax.swing.JTree objectJTree;
    private javax.swing.JPanel sideSplitPanel;
    private javax.swing.JButton tabMap;
    private javax.swing.JButton tabTerrain;
    private javax.swing.JButton tabUnits;
    private pe.edu.pucp.cpnc.mm.view.TileButton tileButton1;
    private pe.edu.pucp.cpnc.mm.view.TileButton tileButton2;
    private pe.edu.pucp.cpnc.mm.view.TileButton tileButton3;
    private javax.swing.JTextField txtMapName;
    private javax.swing.JPanel workingAreaCont;
    // End of variables declaration//GEN-END:variables

    public static int getIsoY(double x, double y){
        return (int)Math.round(((x - Renderer.offsetX - CameraPanController.getCameraPanX())/(double)Renderer.Anchura) + 
                ((y - Renderer.offsetY - Renderer.Altura/2 -CameraPanController.getCameraPanY())/(double)Renderer.Altura));
    }
    
    public static int getIsoX(double x, double y){
        return (int)Math.round(((x - Renderer.offsetX - CameraPanController.getCameraPanX())/(double)Renderer.Anchura) - 
                ((y - Renderer.offsetY - Renderer.Altura/2 - CameraPanController.getCameraPanY())/(double)Renderer.Altura)-1);//j
    }

}
